package com.jason.kotlin.meta.architecture2.ui.fragments

import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.jason.kotlin.meta.R
import com.jason.kotlin.meta.architecture2.base.WanBaseFragment
import com.jason.library.common.adapter.CommonViewPagerAdapter
import com.jason.kotlin.meta.architecture2.viewmodel.ProjectViewModel
import com.jason.library.common.base.Status
import com.jason.library.common.ext.observe
import com.jason.library.common.ext.showToast


class ProjectFragment : WanBaseFragment() {

    private lateinit var viewPager: ViewPager
    private lateinit var tabLayout: TabLayout

    private lateinit var pagerAdapter: CommonViewPagerAdapter

    private lateinit var viewModel: ProjectViewModel

    override fun getLayoutId() = R.layout.fragment_project

    override fun onViewInit(view: View) {
        tabLayout = view.findViewById(R.id.tablayout)
        viewPager = view.findViewById(R.id.viewpager)

        pagerAdapter = CommonViewPagerAdapter(
            childFragmentManager
        )

        viewPager.adapter = pagerAdapter
    }

    override fun onDataInit() {
        viewModel =
            ViewModelProvider.AndroidViewModelFactory.getInstance(activity!!.application).create(
                ProjectViewModel::class.java
            )
        //数据监听
        bindLiveData()

        loadData()
    }

    private fun loadData() {
        viewModel.loadProjectClassify()
    }

    /**
     * 绑定LiveData的监听
     */
    private fun bindLiveData() {

        observe(viewModel.pageStatusData) {
            when (it.status) {
                Status.SUCCESS -> {
                    showToast("加载项目分类数据")
                }
                Status.EMPTY -> showToast("加载不到数据")
                Status.ERROR -> showToast("加载失败")
                Status.LOADING -> showToast("项目分类数据加载中。。。。。。")
            }
        }

        //项目分类-数据监听
        observe(viewModel.classifyData) {
            val classifyList = it.data
            if (classifyList != null) {
                for (classifyBean in classifyList) {
                    pagerAdapter.addFragment(
                        ProjectArticlesFragment.newInstance(classifyBean.id),
                        classifyBean.name
                    )
                }
                pagerAdapter.notifyDataSetChanged()
                viewPager.offscreenPageLimit = classifyList.size
                tabLayout.setupWithViewPager(viewPager)
            }

        }


    }


}